<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-weight: 16">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!-- 添加品牌按钮 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" size="medium"
                 @click="$router.push('/sys-admin/product/brand/add-new')">添加品牌
      </el-button>
    </div>
    <!-- 品牌列表数据-->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="logo" label="Logo" width="60" align="center">
        <template slot-scope="scope">
          <el-avatar :size="'small'" :src="scope.row.logo"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="pinyin" label="拼音" width="140" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="keywords" label="关键词" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="是否启用" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#cccccc">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div style="text-align: right;margin-top: 10px">
      <el-pagination
          @current-change="changePage"
          layout="total,prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :pageSize="pageSize">
      </el-pagination>
    </div>
    <!-- 编辑品牌详情的对话框 -->
    <el-dialog title="修改品牌" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="editForm.pinyin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 分页相关数据
      total: 0,
      pageSize: 20,
      currentPage: 1,
      // 编辑对话框的可见性
      dialogFormVisible: false,
      // 编辑表单
      editForm: {
        id: '',
        name: '',
        pinyin:'',
        description: '',
        keywords:'',
        sort: ''
      },
      // 编辑表单的验证规则
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        pinyin: [
          {required: true, message: '请输入拼音', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入简介', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        keywords: [
          {required: true, message: '请输入关键词，用，隔开', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]?)$/, message: '排序序号必须是0~99之间的数字', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    // 是否启用品牌
    toggleEnable(brand) {
      let enableText = ['禁用', '启用'];
      let url = 'http://localhost:9180/brands/' + brand.id;
      if (brand.enable == 1) {
        url += '/enable';
      } else {
        url += '/disable';
      }
      console.log('url=' + url);
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          let message = '将品牌【' + brand.name + '】的启用状态修改为【' + enableText[brand.enable] + '】成功！';
          this.$message({
            message: message,
            type: 'success'
          });
          this.loadBrandList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    // 提交编辑表单
    submitEditForm() {
      let url = 'http://localhost:9180/brands/' + this.editForm.id + '/update';
      console.log('url' + url);

      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改品牌成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadBrandList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadBrandList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
            }
          });
        }
      })
    },
    // 打开编辑品牌详情对话框
    openEditDialog(brand) {
      let url = 'http://localhost:9180/brands/' + brand.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          console.log('jsonResult.data: ', jsonResult.data);
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }
      })
    },
    // 删除按钮
    openDeleteConfirm(brand) {
      this.$confirm('此操作将永久删除【' + brand.id + '-' + brand.name + '】品牌, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(brand);
      }).catch(() => {

      });

    },
    // 删除功能
    handleDelete(brand) {
      let url = 'http://localhost:9180/brands/' + brand.id + '/delete';
      console.log('url' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            message: '删除品牌成功!'
          });
          this.loadBrandList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    // 切换分页
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadBrandList();
    },
    // 加载品牌列表
    loadBrandList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = 'http://localhost:9180/brands?page=' + page;

      let localJwt = localStorage.getItem('localJwt');
      console.log('Jwt=' + localJwt);
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {

        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          console.log(jsonResult.data);
          console.log(response);
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              // this.$message({
              //   type: 'info',
              //   message: `action: ${ action }`
              // });
            }
          });
        }
      })
    }
  },
  mounted() {
    this.loadBrandList();
  }
}
</script>